package com.yuzhi.master.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ctg.ag.sdk.biz.AepDeviceStatusClient;
import com.ctg.ag.sdk.biz.aep_device_status.QueryDeviceDataBySnRequest;
import com.ctg.ag.sdk.biz.aep_device_status.QueryDeviceDataBySnResponse;
import com.ctg.ag.sdk.core.constant.Scheme;
import com.yuzhi.common.contant.Constants;
import com.yuzhi.common.core.domain.entity.SysDictData;
import com.yuzhi.common.util.redis.CacheUtils;
import com.yuzhi.master.drainRRmst.service.IDrainRRmstService;
import com.yuzhi.master.pump.service.IDrainPumpBjService;
import com.yuzhi.system.domain.request.SysDictDataReq;
import com.yuzhi.system.service.impl.SysDictDataServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName: PumpInfoTask
 * @Author: Mario
 * @Description: 泵站信息定时采集物联网数据任务1分钟执行一次
 */
@Slf4j
@Component
public class PumpInfoTask {

    @Value("${AIoT.appkey}")
    private String appkey;

    @Value("${AIoT.appSecret}")
    private String appSecret;

    @Value("${AIoT.masterKey}")
    private String masterKey;

    @Value("${AIoT.productId}")
    private String productId;

    @Autowired
    private SysDictDataServiceImpl sysDictDataService;

    @Autowired
    private IDrainRRmstService drainRRmstService;

    @Autowired
    private IDrainPumpBjService iDrainPumpBjService;

    private static final String DICT_TYPE = "equipment_device_type";
    private static final String DICT_VALUE = "5";  // 泵站编码对应的字典值
    private static final String CACHE_KEY = "pump_station_codes";

    /**
     * 1分钟执行一次任务
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void execute() {
        log.info("PumpInfoTask任务开始执行！");

        // 1. 先尝试从缓存中获取泵站编码
        Object cachedData = CacheUtils.get(CACHE_KEY, "pump_station_codes_key");

        List<String> pumpStationCodes = null;

        // 判断缓存值是否为 List 类型
        if (cachedData instanceof List) {
            pumpStationCodes = (List<String>) cachedData;
        }

        if (pumpStationCodes == null) {
            // 2. 如果缓存中没有数据，从数据库加载并缓存
            pumpStationCodes = loadPumpStationCodesFromDatabase();
            CacheUtils.putWithExpiration(CACHE_KEY, "pump_station_codes_key", pumpStationCodes, 10, TimeUnit.MINUTES);
            log.info("缓存中没有泵站编码，已从数据库加载并缓存");
        }

        // 3. 遍历泵站编码并查询设备数据
        pumpStationCodes.forEach(this::fetchAndProcessDeviceData);

        log.info("PumpInfoTask任务执行完毕！");
    }


    private List<String> loadPumpStationCodesFromDatabase() {
        // 查询字典数据（泵站编码）
        SysDictDataReq dataReq = new SysDictDataReq();
        dataReq.setDictType(DICT_TYPE);
        dataReq.setDictValue(DICT_VALUE);
        dataReq.setDeleted(Constants.UNDELETED.byteValue());
        List<SysDictData> sysDictData = sysDictDataService.selectDictDataList(dataReq);

        return sysDictData.stream()
                .map(SysDictData::getDictLabel)  // 提取泵站编码
                .filter(StringUtils::isNotBlank)  // 过滤空值
                .distinct()  // 去重
                .collect(Collectors.toList());
    }

    private void fetchAndProcessDeviceData(String deviceSn) {
        log.info("开始查询泵站：{}", deviceSn);

        AepDeviceStatusClient client = AepDeviceStatusClient.newClient()
                .appKey(appkey)
                .appSecret(appSecret)
                .scheme(Scheme.HTTPS)
                .build();
        QueryDeviceDataBySnRequest request = new QueryDeviceDataBySnRequest();
        request.setParamProductId(productId);
        request.setParamDeviceSn(deviceSn);

        try {
            QueryDeviceDataBySnResponse result = client.QueryDeviceDataBySn(request);
            String decodedResponse = new String(result.getBody(), "UTF-8");
            log.info("泵站 {} 查询到设备数据：{}", deviceSn, decodedResponse);
            //判断decodedResponse 里的result 是否为空
            JSONObject decodedResponseJson = JSONObject.parseObject(decodedResponse);
            JSONObject resultJson = decodedResponseJson.getJSONObject("result");
            // 健壮性判断
            if (resultJson == null) {
                log.error("result参数为空，暂不处理");
                return;
            }
            // 处理设备数据逻辑，例如存储到数据库或其他操作
            iDrainPumpBjService.monitoringAnalysis(deviceSn, decodedResponse);
        } catch (Exception e) {
            log.error("查询设备数据异常，设备编号：{}，异常信息：{}", deviceSn, e.getMessage());
        } finally {
            log.info("----存储结束----");
            client.shutdown();
        }
    }
}
